package com.ymtc.ibm.code;

import com.ibm.mq.*;
import com.ibm.mq.constants.MQConstants;

public class MQClientGetGroup {
	private String hostname = "127.0.0.1";
	private int port = 1414; 
	private String channel = "CLIENT.CHL"; 
	private String qManager = "QMA"; 
	private MQQueueManager qMgr; 
	private static String qName = "Q.IN";
	private MQQueue queue;

	public static void main(String[] args) {
		MQClientGetGroup sg = new MQClientGetGroup();
		sg.runGetMsg();
	}

	public MQClientGetGroup() {
	}

	public void MQStart() {
		try {
			MQEnvironment.hostname = hostname; 
			MQEnvironment.channel = channel; 
			MQEnvironment.port = port;
			MQEnvironment.CCSID = 1208;
			
			//Create a connection to the queue manager
			qMgr = new MQQueueManager(qManager);
			int openOptions = MQConstants.MQOO_INPUT_AS_Q_DEF | MQConstants.MQOO_OUTPUT ;
			queue = qMgr.accessQueue(qName, openOptions);
			System.out.println(">>> Open Queue successful!");
		} catch (MQException ex) {
			System.out.println("WebSphere MQ error occurred: Competion code"+ ex.completionCode	+ "Reason Code"	+ ex.reasonCode);
		}
	}

	public void MQStop() {
		try {
			queue.close();
			qMgr.disconnect();
		} catch (MQException ex) {
		}
	}

	public void getMsgToView() {
		try {
			MQGetMessageOptions gmo = new MQGetMessageOptions();
			gmo.options = gmo.options + MQConstants.MQGMO_FAIL_IF_QUIESCING;
			gmo.options = gmo.options + MQConstants.MQGMO_ALL_MSGS_AVAILABLE;
			gmo.options = gmo.options + MQConstants.MQGMO_LOGICAL_ORDER;
			gmo.options = gmo.options + MQConstants.MQGMO_WAIT;
			gmo.options = gmo.options + MQConstants.MQGMO_SYNCPOINT_IF_PERSISTENT;
			
			//gmo.waitInterval = 10;
			//gmo.options = gmo.options + MQConstants.MQGMO_NO_WAIT
			//gmo.waitInterval = MQConstants.MQWI_UNLIMITED;
			//gmo.matchOptions = MQConstants.MQMO_NONE;
			//gmo.matchOptions = MQConstants.MQMO_MATCH_MSG_ID;
			
			System.out.println(">>> Start to get messages!");
			MQMessage msg = new MQMessage();
			String allMsg="";
			String oneMsg="";
			while (true) {				
				queue.get(msg, gmo);
				oneMsg = msg.readLine();
				System.out.println(">>> Get msg content is ------" + oneMsg);
				allMsg += oneMsg;
				System.out.println(">>> All message is : " + allMsg);
				char y = gmo.groupStatus;
				System.out.println(">>> Group status : " + y);
				if (y == MQConstants.MQGS_LAST_MSG_IN_GROUP){
					System.out.println(">>> All message successfully Receive!");
					break;
				}
				msg.clearMessage();
			}			
		} catch (Exception ex) {
			ex.printStackTrace(System.out);
		}
	}
	
	public void runGetMsg() {
		try {
			MQStart();
			getMsgToView();
			MQStop();
		} catch (Exception e) {
			e.printStackTrace();
			MQStop();
			System.exit(2);
		}
	}
}